package cn.trigram.json.deserializer;

import cn.trigram.exception.JsonDeserializerException;
import cn.trigram.json.annotation.BigNumberDeserializer;
import cn.trigram.lang.BigMathUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.std.NumberDeserializers;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

/**
 * 大数反序列化
 *
 * @version 1.0.0
 * @date 2022/08/23 10:09:09
 * @since 1.0.0
 */
public class BigNumberContextualDeserializer extends JsonDeserializer<BigDecimal> implements ContextualDeserializer {

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) {
        final BigNumberDeserializer annotation = Optional.ofNullable(property).map(p -> p.getAnnotation(BigNumberDeserializer.class)).orElse(null);
        final Class<? extends Number> rawClass = (Class<? extends Number>) Optional.ofNullable(property).map(BeanProperty::getType)
                .map(JavaType::getRawClass).orElse(null);
        if (Objects.equals(rawClass, BigDecimal.class)) {
            if (Objects.isNull(annotation) || annotation.useJackson()) {
                return new SoftReference<JsonDeserializer<?>>(new NumberDeserializers.BigDecimalDeserializer()).get();
            } else {
                return new SoftReference<JsonDeserializer<?>>(new BigDecimalDeserializer(annotation)).get();
            }
        } else {
            return new SoftReference<JsonDeserializer<?>>(NumberDeserializers.find(rawClass, rawClass.getName())).get();
        }
    }

    @Override
    public BigDecimal deserialize(JsonParser p, DeserializationContext ctxt) {
        return null;
    }

    /**
     * @version 1.0.0
     * @date 2022/08/02 16:09:59
     * @since 1.0.0
     */
    @JacksonStdImpl
    public static class BigDecimalDeserializer extends StdDeserializer<BigDecimal> {
        private final BigNumberDeserializer deserializer;
        private static final Pattern COMMA = Pattern.compile(",");

        public BigDecimalDeserializer(BigNumberDeserializer deserializer) {
            super(BigDecimal.class);
            this.deserializer = deserializer;
        }

        @Override
        public BigDecimal deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            String text = p.getValueAsString();
            if (StringUtils.isBlank(text)) {
                return getNullValue(ctxt);
            }
            final String pattern = this.deserializer.pattern();
            if (StringUtils.isNotBlank(pattern)) {
                try {
                    final DecimalFormat decimalFormat = new DecimalFormat(pattern);
                    decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
                    decimalFormat.setParseBigDecimal(true);
                    final Number number = decimalFormat.parse(text);
                    if (number instanceof BigDecimal) {
                        return (BigDecimal) number;
                    } else {
                        return BigDecimal.valueOf(number.doubleValue());
                    }
                } catch (ParseException e) {
                    if (this.deserializer.ignoreException()) {
                        return null;
                    } else {
                        throw new JsonDeserializerException("反序列化BigDecimal失败，原值：" + text, e);
                    }
                }
            } else {
                final BigNumberDeserializer.Model model = this.deserializer.model();
                if (model.equals(BigNumberDeserializer.Model.DEFAULT)) {
                    if (text.contains(",")) {
                        text = COMMA.matcher(text).replaceAll("");
                    }
                    return new BigDecimal(text, MathContext.UNLIMITED);
                } else if (model.equals(BigNumberDeserializer.Model.TEN_THOUSAND_YUAN) || model.equals(BigNumberDeserializer.Model.TEN_THOUSAND_YUAN_THOUSANDS)) {
                    if (text.contains(",")) {
                        text = COMMA.matcher(text).replaceAll("");
                    }
                    return new BigDecimal(text, MathContext.UNLIMITED).multiply(BigMathUtil.HUNDRED).multiply(BigMathUtil.HUNDRED);
                } else if (model.equals(BigNumberDeserializer.Model.PERCENTAGE) || model.equals(BigNumberDeserializer.Model.PERCENTAGE_WITH_SYMBOL)) {
                    if (text.endsWith("%")) {
                        text = text.replaceAll("%", "");
                    }
                    return new BigDecimal(text, MathContext.UNLIMITED).divide(BigMathUtil.HUNDRED, MathContext.UNLIMITED);
                } else {
                    return new SoftReference<>(new NumberDeserializers.BigDecimalDeserializer()).get().deserialize(p, ctxt);
                }
            }

        }

    }
}
